package test.ground.es;

import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;

/**
 * @Author wangshaopeng
 * @Date 2021/5/9
 */
public class EsStart {

    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")));
//        createIndex(client);

//        delIndex(client);

//        createDocument(client);


        queryDoc(client);



    }

    private static void queryDoc(RestHighLevelClient client) throws IOException {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.termQuery("shopname", "1"));
        SearchRequest request = new SearchRequest("test-alias1");
        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits.getHits()) {
            System.out.println(hit.getSourceAsString());
        }
    }

    private static void createDocument(RestHighLevelClient client) throws IOException {
        IndexRequest request = new IndexRequest("test2");
        request.type("_doc");
        request.id("1213").source("{\"shopname\":\"店铺名称1\",\"shopid\":\"2345\"}",XContentType.JSON);
        client.index(request, RequestOptions.DEFAULT);

    }

    private static void delIndex(RestHighLevelClient client) throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("test1");
        client.indices().delete(request,RequestOptions.DEFAULT);

    }

}
